package com.sky.websocket;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {
    private static Map<String, Session> sessionMap=new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid){
        System.out.println("用户"+sid+"已连接");
        sessionMap.put(sid,session);
    }
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid){
        System.out.println("用户"+sid+"发来消息："+message);
    }
    @OnClose
    public void onClose(@PathParam("sid") String sid){
        System.out.println("用户"+sid+"已断开");
        sessionMap.remove(sid);
    }
    public void sendToAllClient(String message){
        for(Session session:sessionMap.values()){
            try{
                session.getBasicRemote().sendText(message);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
